package com.rankeiot.platform.controller;

import com.rankeiot.core.Current;
import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.platform.config.PlatformConfig;
import com.rankeiot.platform.service.IFileStoreService;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.IOException;


@Auth
@Controller
@RequiredArgsConstructor
public class FileController {

    final IFileStoreService fileStoreService;


    @PostMapping(value = "/file/upload")
    @ResponseBody
    public Resp<String> upload(MultipartFile file) throws IOException {
        UserInfo userInfo=Current.user();
        String user = userInfo.getUserType()+userInfo.getId();
        return fileStoreService.save(file, user);
    }

    @PostMapping(value = "/file/delete")
    @ResponseBody
    public Resp delete(String path) {
        UserInfo userInfo=Current.user();
        String user = userInfo.getUserType()+userInfo.getId();
        return fileStoreService.delete(path,user);
    }

    @Auth(login = false)
    @RequestMapping("/files/**")
    public ResponseEntity getFile(HttpServletRequest request) {
        if(PlatformConfig.FileSec.value().asBoolean()){
           if(Current.user()==null){
               Resp.fail("没有权限");
           }
        }
        String path=UriUtils.decode(request.getRequestURI(),"UTF-8");

        return fileStoreService.getFile(path,request.getQueryString());
    }
    @Auth(login = false)
    @RequestMapping("/path")
    @ResponseBody
    public String fullPath(HttpServletRequest request,String file){
        String prefix=request.getRequestURL().toString().replaceFirst("/path$","/");
        return fileStoreService.getFullPath(file,prefix);
    }
    @Auth
    @GetMapping("/file/policy")
    @ResponseBody
    public Resp policy(String fileName){
        UserInfo userInfo=Current.user();
        String user = userInfo.getUserType()+userInfo.getId();
        return Resp.of(fileStoreService.policy(fileName,user));
    }
}
